package servlet;

import dao.Messagedao;
import vo.Message;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

@WebServlet("/MessageServlet")
public class MessageServlet extends HttpServlet {
    private Messagedao messageDAO = new Messagedao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session= request.getSession();
        User user= (User) session.getAttribute("user");
        String username= user.getUsername();
        String text = request.getParameter("text");
        Date time = new Date();
        Message message = new Message(username, text, time);
        try {
            messageDAO.addMessage(message);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        try {
            session.setAttribute("messages", messageDAO.getAllMessages());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        request.getRequestDispatcher("/chatroom.jsp").forward(request, response);
    }
}

